<template>
  <div :style="{height:printHeight}">
    <!-- 表头 -->
    <div class="header" style="background:#F5F7FA;">
      <div v-for="head in headers" :key="head.prop" :style="setStyle(head)">
        {{ head.label }}
      </div>
    </div>

    <!-- 表体 -->
    <div :key="count" class="table-centent" :style="setScrollHeight()">
      <div v-for="(item,index) in tableData" :ref="item.prop+index" :key="item.prop" class="row">
        <div v-for="(head) in headers" :key="head.prop" :style="setStyle(head,item.height)">
          {{ item[head.prop] }}
        </div>
      </div>
    </div>

  </div>
</template>

<script>
export default {
  name: "Print",
  props: {
    // 表头
    headers: {
      type: Array,
      require: true,
      default: () => []
    },
    // 内容
    data: {
      type: Array,
      require: true,
      default: () => []
    },
    // 是否是展示的打印区域
    isExhibition: {
      type: Boolean,
      default: true
    },
    // 当前打印页面表格总高度
    printHeight: {
      type: [String],
      default: ""
    },
    // 表头前面 插槽的 高度
    headSlotHeight: {
      type: Number,
      default: 0
    },
    // 表格后面 插槽的 高度
    bottomSlotHeight: {
      type: Number,
      default: 0
    },
    // 默认表格高度
    defaultTableHeight: {
      type: Number,
      default: 460
    }

  },
  data() {
    return {
      tableData: [],
      // 表格内容默认高度
      tableDefaultHeight: 30,
      // 更新表体时使用
      count: 1
      // 打印属性
    };
  },
  watch: {
    data: {
      handler() {
        this.getTableheight();
      },
      deep: true,
      // 初始化执行
      immediate: true
    }
  },
  methods: {
    // 设置表格可滚动的高度
    setScrollHeight() {
      let height = "";
      // 插槽占据的盖度
      const slotHeight = this.headSlotHeight + this.bottomSlotHeight;

      if (slotHeight) {
        height = ((slotHeight && slotHeight <= this.defaultTableHeight) ? this.defaultTableHeight - slotHeight : this.defaultTableHeight) + "px";
      }

      return {
        height
      };
    },
    // 计算表格的高度
    getTableheight() {
      this.tableData = this.data;

      // 表格的高度
      const tableHeight = [];
      this.$nextTick(() => {
        this.tableData.forEach((item, index) => {
          const height = this.$refs[item.props + index][index]?.clientHeight || this.tableDefaultHeight;
          item.height = height + "px";
          tableHeight.push(height);
        });
        // 获取高度后重新强制渲染表体
        this.count++;
        if (this.isExhibition) {
          // 数据的总高度
          this.$emit("table-height", tableHeight);
        }
      });
    },
    setStyle(item, height = "") {
      const { width, align } = item || {};
      const style = {
        width: width,
        flex: width ? "" : 1,
        justifyContent: align,
        height
      };
      return style;
    }
  }
};
</script>

<style  lang="scss" src="./index.scss"></style>
